<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="profile-sidebar" shadow="hover">
          <div class="avatar-container">
            <el-avatar 
              :size="120" 
              :src="getAvatarUrl(userInfo.avatarUrl)" 
              @error="handleAvatarError"
            />
            <h2 class="user-name">{{ userInfo.name }}</h2>
            <div class="user-role">{{ userInfo.employeeType }}</div>
            <el-button type="primary" size="small" class="avatar-btn" @click="showAvatarDialog">更换头像</el-button>
          </div>
          
          <el-divider />
          
          <div class="quick-info">
            <div class="info-item">
              <div class="info-label"><el-icon><User /></el-icon> 工号</div>
              <div class="info-value">{{ userInfo.employeeNo }}</div>
            </div>
            <div class="info-item">
              <div class="info-label"><el-icon><Phone /></el-icon> 联系电话</div>
              <div class="info-value">{{ userInfo.phone }}</div>
            </div>
            <div class="info-item">
              <div class="info-label"><el-icon><Calendar /></el-icon> 入职日期</div>
              <div class="info-value">{{ formatDate(userInfo.hireDate) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-tabs v-model="activeTab" class="profile-tabs" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-card class="profile-card" v-loading="loading.userInfo" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>个人详细信息</span>
                </div>
              </template>
              
              <el-descriptions :column="2" border>
                <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="工号">{{ userInfo.employeeNo }}</el-descriptions-item>
                <el-descriptions-item label="角色">{{ userInfo.employeeType }}</el-descriptions-item>
                <el-descriptions-item label="部门">{{ userInfo.department }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ userInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="入职日期">{{ formatDate(userInfo.hireDate) }}</el-descriptions-item>
                <el-descriptions-item label="性别">{{ formatGender(userInfo.gender) }}</el-descriptions-item>
                <el-descriptions-item label="联系地址" :span="2">{{ userInfo.address || '未设置' }}</el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-tab-pane>
          
          <el-tab-pane label="修改密码" name="password">
            <el-card class="profile-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span>安全设置</span>
                </div>
              </template>
              
              <el-form 
                :model="passwordForm" 
                :rules="passwordRules" 
                ref="passwordFormRef"
                label-width="120px"
                class="password-form">
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input 
                    v-model="passwordForm.oldPassword" 
                    type="password" 
                    show-password
                    placeholder="请输入当前密码" />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input 
                    v-model="passwordForm.newPassword" 
                    type="password" 
                    show-password
                    placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password" 
                    show-password
                    placeholder="请再次输入新密码" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleChangePassword" :loading="loading.password">修改密码</el-button>
                  <el-button @click="resetPasswordForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 头像选择对话框 -->
    <el-dialog title="选择头像" v-model="avatarDialogVisible" width="500px">
      <div class="avatar-select-container">
        <h4>预设头像</h4>
        <div class="preset-avatars">
          <div 
            v-for="i in 12" 
            :key="i" 
            class="preset-avatar-item"
            :class="{ active: selectedPresetAvatar === i }"
            @click="selectPresetAvatar(i)">
            <img :src="require(`@/assets/images/avatar/${i}.png`)" :alt="`头像${i}`" />
          </div>
        </div>
        
        <el-divider>或上传自定义头像</el-divider>
        
        <el-upload
          class="custom-avatar-upload"
          action="#"
          :auto-upload="false"
          :show-file-list="true"
          :limit="1"
          :on-change="handleCustomAvatarChange"
          :on-exceed="handleExceed"
          accept="image/jpeg,image/png,image/gif">
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">只能上传JPG/PNG/GIF文件，且不超过2MB</div>
          </template>
        </el-upload>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="avatarDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAvatarChange" :loading="loading.avatar">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Phone, Calendar } from '@element-plus/icons-vue'
import { getCurrentUserInfo, changePassword, getUserWorkOrders, updateAvatar } from '@/api/users'

// 导入预设头像
const presetAvatars = {}
for (let i = 1; i <= 12; i++) {
  presetAvatars[i] = require(`@/assets/images/avatar/${i}.png`)
}

// API基础URL，用于构建完整的头像URL
const API_BASE_URL = process.env.VUE_APP_API_URL || ''

export default {
  name: 'StaffProfile',
  components: {
    User,
    Phone,
    Calendar
  },
  setup() {
    const router = useRouter()
    const activeTab = ref('basic')
    const passwordFormRef = ref(null)
    
    // 加载状态
    const loading = reactive({
      userInfo: false,
      password: false,
      historyOrders: false,
      avatar: false
    })
    
    // 用户信息
    const userInfo = reactive({
      userId: null,
      username: '',
      name: '',
      employeeNo: '',
      employeeType: '',
      department: '',
      phone: '',
      hireDate: '',
      gender: '',
      address: '',
      avatarUrl: ''
    })
    
    // 修改密码表单
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码表单校验规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ]
    }
    
    // 历史工单数据
    const historyOrders = ref([])
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 工单筛选条件
    const orderFilter = reactive({
      type: '',  // repair, cleaning, water
      dateRange: []
    })
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          return [start, end]
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          return [start, end]
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          return [start, end]
        }
      }
    ]
    
    // 获取工单类型标签
    const getOrderTypeTag = (type) => {
      const typeMap = {
        repair: 'danger',
        cleaning: 'success',
        water: 'info'
      }
      return typeMap[type] || ''
    }
    
    // 获取工单类型文本
    const getOrderTypeText = (type) => {
      const typeMap = {
        repair: '维修',
        cleaning: '保洁',
        water: '送水'
      }
      return typeMap[type] || '未知'
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const statusMap = {
        '待受理': 'info',
        '已受理': 'warning',
        '处理中': 'warning',
        '服务中': 'warning',
        '配送中': 'warning',
        '已完成': 'success',
        '已送达': 'success',
        '已评价': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || ''
    }
    
    // 格式化性别
    const formatGender = (gender) => {
      if (gender === 'M' || gender === 1) return '男'
      if (gender === 'F' || gender === 2) return '女'
      return '未设置'
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }
    
    // 查看工单详情
    const viewOrderDetail = (id, type) => {
      router.push(`/staff/work-order/${id}?type=${type}`)
    }
    
    // 处理分页变化
    const handlePageChange = (page) => {
      pagination.currentPage = page
      fetchHistoryOrders()
    }
    
    // 处理修改密码
    const handleChangePassword = async () => {
      if (!passwordFormRef.value) return
      
      try {
        await passwordFormRef.value.validate()
        loading.password = true
        
        // 调用API修改密码
        const response = await changePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        
        if (response.data && response.data.code === 200) {
          ElMessage.success('密码修改成功')
          resetPasswordForm()
        } else {
          ElMessage.error(response.data?.message || '密码修改失败')
        }
        
        loading.password = false
      } catch (error) {
        console.error('修改密码失败', error)
        ElMessage.error(error.response?.data?.message || '密码修改失败')
        loading.password = false
      }
    }
    
    // 重置密码表单
    const resetPasswordForm = () => {
      if (passwordFormRef.value) {
        passwordFormRef.value.resetFields()
      }
    }
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      loading.userInfo = true
      try {
        // 调用API获取用户信息
        const response = await getCurrentUserInfo()
        
        if (response.data) {
          // 从响应中提取用户信息
          const userData = response.data
          
          // 更新用户信息
          userInfo.userId = userData.user_id
          userInfo.username = userData.username
          userInfo.name = userData.name || userData.username
          userInfo.phone = userData.phone
          userInfo.avatarUrl = userData.avatar_url
          
          // 如果是园区员工，获取额外信息
          if (userData.user_type === 'park_employee' && userData.profile) {
            userInfo.employeeNo = userData.profile.employee_no
            userInfo.employeeType = userData.profile.employee_type
            userInfo.department = userData.profile.department
            userInfo.hireDate = userData.profile.hire_date
            // 确保性别字段正确获取
            if (userData.profile && userData.profile.gender) {
              userInfo.gender = userData.profile.gender
            } else if (userData.gender) {
              userInfo.gender = userData.gender
            }
            userInfo.address = userData.profile.address
          } else {
            // 处理非园区员工的情况
            if (userData.gender) {
              userInfo.gender = userData.gender
            } else if (userData.profile && userData.profile.gender) {
              userInfo.gender = userData.profile.gender
            }
          }
          
          console.log('用户信息:', userInfo)
        }
        
        loading.userInfo = false
      } catch (error) {
        console.error('获取用户信息失败', error)
        ElMessage.error('获取用户信息失败')
        loading.userInfo = false
      }
    }
    
    // 获取历史工单
    const fetchHistoryOrders = async () => {
      loading.historyOrders = true
      try {
        // 构建查询参数
        const params = {
          page: pagination.currentPage,
          pageSize: pagination.pageSize,
          type: orderFilter.type,
          startDate: orderFilter.dateRange && orderFilter.dateRange.length > 0 ? orderFilter.dateRange[0] : null,
          endDate: orderFilter.dateRange && orderFilter.dateRange.length > 0 ? orderFilter.dateRange[1] : null
        }
        
        // 调用API获取历史工单
        const response = await getUserWorkOrders(params)
        
        if (response.data && response.data.code === 200) {
          historyOrders.value = response.data.data.list
          pagination.total = response.data.data.total
        } else {
          ElMessage.error('获取历史工单失败')
        }
        
        loading.historyOrders = false
      } catch (error) {
        console.error('获取历史工单失败', error)
        ElMessage.error('获取历史工单失败')
        loading.historyOrders = false
      }
    }
    
    // 头像选择相关
    const avatarDialogVisible = ref(false)
    const selectedPresetAvatar = ref(null)
    const customAvatarFile = ref(null)
    
    // 显示头像选择对话框
    const showAvatarDialog = () => {
      avatarDialogVisible.value = true
      selectedPresetAvatar.value = null
      customAvatarFile.value = null
    }
    
    // 选择预设头像
    const selectPresetAvatar = (index) => {
      selectedPresetAvatar.value = index
      customAvatarFile.value = null
    }
    
    // 处理自定义头像选择
    const handleCustomAvatarChange = (file) => {
      // 验证文件类型
      const acceptTypes = ['image/jpeg', 'image/png', 'image/gif']
      if (!acceptTypes.includes(file.raw.type)) {
        ElMessage.error('请上传JPG/PNG/GIF格式的图片')
        return false
      }
      
      // 验证文件大小（限制为2MB）
      if (file.size / 1024 / 1024 > 2) {
        ElMessage.error('头像文件大小不能超过2MB')
        return false
      }
      
      customAvatarFile.value = file
      selectedPresetAvatar.value = null
    }
    
    // 处理文件数量超出限制
    const handleExceed = () => {
      ElMessage.warning('只能上传一个文件')
    }
    
    // 处理头像加载错误
    const handleAvatarError = () => {
      // 如果头像加载失败，使用默认头像
      userInfo.avatarUrl = ''
    }
    
    // 获取头像URL
    const getAvatarUrl = (url) => {
      if (!url) {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      
      // 如果是base64数据，直接返回
      if (url.startsWith('data:image/')) {
        return url
      }
      
      // 如果是预设头像路径
      if (url.startsWith('/assets/images/avatar/')) {
        try {
          const avatarNumber = parseInt(url.split('/').pop().split('.')[0])
          if (avatarNumber >= 1 && avatarNumber <= 12) {
            return presetAvatars[avatarNumber]
          }
        } catch (e) {
          console.error('解析头像路径失败', e)
        }
      }
      
      // 如果是自定义头像标识符
      if (url.startsWith('custom_')) {
        // 使用默认头像，因为实际图像数据已经在前端处理
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      
      // 如果是服务器上传的头像
      if (url.startsWith('/media/')) {
        // 添加API基础URL
        return `${API_BASE_URL}${url}`
      }
      
      // 其他情况直接返回URL
      return url
    }
    
    // 确认更换头像
    const confirmAvatarChange = async () => {
      if (!selectedPresetAvatar.value && !customAvatarFile.value) {
        ElMessage.warning('请选择头像或上传图片')
        return
      }
      
      loading.avatar = true
      try {
        if (selectedPresetAvatar.value) {
          // 使用预设头像
          const presetPath = `/assets/images/avatar/${selectedPresetAvatar.value}.png`
          const response = await updateAvatar({
            preset_avatar: presetPath
          })
          
          if (response.data && response.data.code === 200) {
            userInfo.avatarUrl = response.data.avatar_url
            ElMessage.success('头像更新成功')
            avatarDialogVisible.value = false
          } else {
            ElMessage.error(response.data?.message || '头像更新失败')
          }
        } else if (customAvatarFile.value) {
          // 上传自定义头像
          const formData = new FormData()
          formData.append('avatar', customAvatarFile.value.raw)
          
          // 同时将文件转换为base64，用于本地显示
          const reader = new FileReader()
          reader.readAsDataURL(customAvatarFile.value.raw)
          reader.onload = async (e) => {
            const base64Data = e.target.result
            
            try {
              const response = await updateAvatar(formData)
              if (response.data && response.data.code === 200) {
                // 使用base64数据直接显示头像，而不是使用服务器返回的URL
                userInfo.avatarUrl = base64Data
                ElMessage.success('头像更新成功')
                avatarDialogVisible.value = false
              } else {
                ElMessage.error(response.data?.message || '头像更新失败')
              }
            } catch (error) {
              console.error('上传头像失败', error)
              ElMessage.error(error.response?.data?.message || '头像更新失败')
            } finally {
              loading.avatar = false
            }
          }
          
          reader.onerror = () => {
            ElMessage.error('读取文件失败')
            loading.avatar = false
          }
          
          // 这里不需要设置loading.avatar = false，因为它会在reader.onload回调中设置
          return
        }
      } catch (error) {
        console.error('更新头像失败', error)
        ElMessage.error(error.response?.data?.message || '头像更新失败')
      } finally {
        loading.avatar = false
      }
    }
    
    onMounted(() => {
      fetchUserInfo()
      fetchHistoryOrders()
    })
    
    return {
      activeTab,
      loading,
      userInfo,
      passwordForm,
      passwordRules,
      passwordFormRef,
      historyOrders,
      pagination,
      orderFilter,
      dateShortcuts,
      getOrderTypeTag,
      getOrderTypeText,
      getStatusType,
      formatDate,
      formatGender,
      viewOrderDetail,
      handlePageChange,
      handleChangePassword,
      resetPasswordForm,
      fetchHistoryOrders,
      // 头像相关
      avatarDialogVisible,
      selectedPresetAvatar,
      showAvatarDialog,
      selectPresetAvatar,
      handleCustomAvatarChange,
      handleExceed,
      confirmAvatarChange,
      getAvatarUrl,
      handleAvatarError
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.profile-sidebar {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.user-name {
  margin: 15px 0 5px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.user-role {
  color: #909399;
  font-size: 14px;
  margin-bottom: 15px;
}

.avatar-btn {
  margin-top: 10px;
}

.quick-info {
  padding: 0 10px;
}

.info-item {
  margin-bottom: 15px;
}

.info-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.info-label .el-icon {
  margin-right: 5px;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.profile-tabs {
  border-radius: 8px;
  overflow: hidden;
}

.profile-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.password-form {
  max-width: 500px;
  margin: 20px auto;
}

.filter-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.avatar-select-container {
  padding: 10px;
}

.preset-avatars {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
  margin: 20px 0;
}

.preset-avatar-item {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.preset-avatar-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.preset-avatar-item.active {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.preset-avatar-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.custom-avatar-upload {
  margin-top: 20px;
  text-align: center;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .el-col-6 {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .el-col-18 {
    width: 100%;
  }
}
</style> 